# 员工
class Admin::EmployeesController < Admin::ApplicationController
  layout "admin"
  before_action :set_employee, only: [:show, :edit, :update, :destroy]
  before_action :authorize_employee
  def index

    @studios = current_company.studios
    @departments = current_company.department_configurations
    @positions = current_company.position_configurations

    params[:studio] ||= "all"
    params[:department] ||= "all"
    params[:sex] ||= "all"
    params[:position] ||= "all"
    params[:birthday] ||= false
    params[:status] ||= "all"


    conditions = ["1=1"]
    conditions << "employee_of_studios.studio_company_id = #{current_company.id}"
    conditions << "employee_of_studios.department_id = '#{params[:department].to_i }'" if params[:department].present? && params[:department] != "all"
    conditions << "employees.sex = '#{params[:sex]}'" if params[:sex].present? && params[:sex] != "all"
    conditions << "position_configurations.position_name = '#{params[:position]}'" if params[:position].present? && params[:position] != "all"
    conditions << "employees.birthday between '#{Time.current.beginning_of_month.to_s(:db)}' and '#{Time.current.end_of_month.to_s(:db)}'" if params[:birthday].to_b
    conditions << "employees.status = '#{params[:status]}'" if params[:status].present? && params[:status] != "all"
    conditions << "studios.id in '#{params[:studio]}'" if params[:studio].present? && params[:studio] != "all"

    @employees = Employee.joins("left join employee_of_studios on employee_of_studios.employee_id = employees.id")
      .joins("left join studios on studios.id = employee_of_studios.studio_id")
      .joins("left join position_configurations on position_configurations.company_id = studios.company_id")
      .where(conditions.join(" and "))
      .uniq
      .paginate(page: params[:page], per_page: 10)
  end

  def get_employee
    @studios = current_company.studios
    @departments = current_company.department_configurations
    @positions = current_company.position_configurations

    params[:studio] ||= "all"
    params[:department] ||= "all"
    params[:sex] ||= "all"
    params[:position] ||= "all"
    params[:birthday] ||= false
    params[:status] ||= "all"

    conditions = ["1=1"]
    conditions << "employee_of_studios.studio_company_id = #{current_company.id}"
    conditions << "employee_of_studios.department_id = '#{params[:department].to_i }'" if params[:department].present? && params[:department] != "all"
    conditions << "employees.sex = '#{params[:sex]}'" if params[:sex].present? && params[:sex] != "all"
    conditions << "employee_of_studios.position_id = '#{params[:position].to_i}'" if params[:position].present? && params[:position] != "all"
    conditions << "employees.birthday between '#{Time.current.beginning_of_month.to_s(:db)}' and '#{Time.current.end_of_month.to_s(:db)}'" if params[:birthday].to_b
    conditions << "employees.status = '#{params[:status]}'" if params[:status].present? && params[:status] != "all"
    conditions << "studios.id in (#{params[:studio]})" if params[:studio].present? && params[:studio] != "all"

    @employees = Employee.joins("left join employee_of_studios on employee_of_studios.employee_id = employees.id")
      .joins("left join studios on studios.id = employee_of_studios.studio_id")
      .joins("left join position_configurations on position_configurations.company_id = studios.company_id")
      .where(conditions.join(" and "))
      .uniq
      .paginate(page: params[:page], per_page: 10)
    respond_to do |format|
      format.js
    end
  end

  def new
    @employee = Employee.new
    @departments = current_company.department_configurations.where.not(department_name: '主理人')
    @positions = current_company.position_configurations.where.not(position_name: '主理人')
    if current_company.employee_of_studios.where(position_name: '财务总监').exists?
      @positions = current_company.position_configurations.where.not(position_name: '财务总监')
    end
    @teacher_levels = current_company.teacher_level_configurations
    @studios = current_company.studios
    @welfares = current_company.employee_welfare_configurations
  end

  def create
    p '=========账户信息============='
    p params[:user].values
    user = User.mobile_with(user_params[0]["mobile"])
    if user.blank?
      user = User.new(user_params[0])
      user.save!
    end

    p '=========基本信息============='
    p employee_params[0]
    employee = Employee.new(employee_params[0])
    employee.company_id = current_company.id
    employee.user_id = user.id
    employee.joined_at = DateTime.now
    employee.status = '在职'
    employee.save!

    p '=========职位信息============='
    p employee_of_studio_params
    employee_of_studio_params.each do |e_params|
      age_group = e_params.delete(:age_group)
      dance_type = e_params.delete(:dance_type)
      teacher_level = e_params.delete(:teacher_level)
      employee_of_studio = EmployeeOfStudio.new(e_params)
      employee_of_studio.position_name = PositionConfiguration.find(e_params['position_id']).position_name
      employee_of_studio.studio_company_id = Studio.find(e_params['studio_id']).company_id
      employee_of_studio.employee_id = employee.id
      employee_of_studio.employee_user_id = employee.user_id
      employee_of_studio.save!

      if employee_of_studio.position_name=="导师"
        teacher = Teacher.new()
        teacher.name = employee.name
        teacher.age_group = age_group
        teacher.dance_type = dance_type
        teacher.teacher_level = teacher_level if teacher_level
        teacher.employee_of_studio_id = employee_of_studio.id
        teacher.studio_id = employee_of_studio.studio_id
        teacher.company_id = employee_of_studio.studio_company_id
        teacher.save!
      end
    end

    p '=========薪资信息============='
    p salary_params
    salary_params.each do |salary_param|
      employee_welfare_id = salary_param.delete(:employee_welfare_id)
      salary = Salary.new(salary_param)
      if employee_welfare_id
        welfare = EmployeeWelfareConfiguration.find(employee_welfare_id)
        salary.amount = welfare.amount
        salary.salary_type= salary_param[:salary_type] + '_' + welfare.welfare_name
      end
      salary.employee_id = employee.id
      salary.employee_user_id = employee.user_id
      salary.save!
    end
    respond_to do |format|
      format.js { render :js => "window.location.href = '/admin/employees'" }
    end

  end

  # 员工信息编辑模块，keivn
  def edit

    respond_to do |format|
      format.html {
        @studios = current_company.studios
        @welfares = current_company.employee_welfare_configurations
        @teacher_levels = current_company.teacher_level_configurations
      }
      format.json { render json: Employees::EditService.call(@employee)}
    end
  end

  def update

    respond_to do |format|

      result = Employees::UpdateService.call(view_context,@employee)
      if result.success
        format.json { render json: result,status: :ok }
      else
        format.json { render json: result, status: :unprocessable_entity }
      end
    end
  end

	def show
		@employee_of_studios = @employee.employee_of_studios
    @basic_salary = @employee.salaries.find_by_salary_type('基本工资')
    @teachers = @employee.salaries.where("salary_type like '导师%'")
    @product_director_salaries = @employee.salaries.where(salary_type: '产品总监_团队超出指标提成')
    @course_salary = @employee.salaries.find_by_salary_type('导师_课时费')
    @fixed_salary = @employee.salaries.find_by_salary_type('导师_固定提成')
    @staged_salaries = @employee.salaries.where(salary_type: '导师_阶段提成')
    @teacher_salaries= @employee.salaries.where(salary_type: '导师_超出指标提成')
    @private_salary = @employee.salaries.find_by_salary_type('导师_私教提成')
    @service_director_salaries = @employee.salaries.where(salary_type: '运营总监_团队超出指标提成')
    @service_salaries = @employee.salaries.where(salary_type: '服务顾问_超出指标提成')
    @market_director_salaries = @employee.salaries.where(salary_type: '市场总监_团队超出指标提成')
    @market_salaries = @employee.salaries.where(salary_type: '市场专员_超出指标提成')
    @welfares = @employee.salaries.where("salary_type like  '福利补助%'")
	end

  private
  def set_employee
    @employee = Employee.find(params[:id])
  end

  def user_params
    params.permit(user: [:mobile, :password, :password_confirmation])[:user].values
  end

  def employee_params
    if action_name=="create"
      params.permit(employee: [:name, :alias_name, :sex, :birthday, :weixin, :mobile, :emergency_contact, :emergency_mobile, :address, :remark , :avatar])[:employee].values
    else
      params.require(:employee).permit(:name, :alias_name, :sex, :birthday, :weixin, :mobile, :emergency_contact, :emergency_mobile, :address, :remark , :avatar)
    end
  end

  def employee_of_studio_params
    if action_name=="create"
      params.permit(employee_of_studio: [:position_id, :department_id, :studio_id, :age_group, :dance_type, :teacher_level])[:employee_of_studio].values
    else
      params.require(:employee_of_studio).permit(:position_id, :department_id, :studio_id, :age_group, :dance_type, :teacher_level)
    end
  end

  def salary_params
    params.permit(salary: [:salary_type, :employee_welfare_id, :amount, :range_min, :range_max])[:salary].try(:values) || []
  end

  #员工权限验证
  def authorize_employee
    authorize Employee,:index?
  end


end
